package base;

import framework.AbstractTest;
import utils.Log;

import java.io.*;
import java.lang.reflect.Constructor;
import java.nio.ByteBuffer;

/**
 * Created by shane on 2018/6/3.
 */
public class ObjectCreator extends AbstractTest implements Serializable, Cloneable {

    private static final String TAG = ObjectCreator.class.getName();
    private static final long serialVersionUID = 4345295815809037360L;

    String name;

    @Override
    public String toString() {
        return "name:" + name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void test(String[] args) {
        super.test(args);

        // 1
        ObjectCreator obj = new ObjectCreator();
        obj.setName("new ObjectCreator()");
        Log.vn(obj.toString());
        try {
            // 2
            Constructor constructor = Class.forName(TAG).getConstructor(null);
            Object object = constructor.newInstance(null);
            obj = (ObjectCreator) object;
            obj.setName("Class.forName(TAG).getConstructor");
            Log.vn(obj.toString());

            // 3
            object = Class.forName(TAG).newInstance();
            obj = (ObjectCreator) object;
            obj.setName("Class.forName(TAG).newInstance()");
            Log.vn(obj.toString());

            // 4
            obj.setName("implements Serializable");
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(256);
            ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
            out.writeObject(obj);
            out.close();

            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            ObjectCreator newObj = (ObjectCreator)in.readObject();
            in.close();
            Log.vn(newObj.toString());

            ObjectCreator cloneObj = (ObjectCreator)newObj.clone();
            cloneObj.setName("newObj.clone()");

            Log.vn(cloneObj.toString());
            Log.vn(newObj.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String getTag() {
        return TAG;
    }
}
